package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.search.pojos.ApAssociateWords;
import com.heima.search.mapper.ApAssociateWordsMapper;
import com.heima.search.model.Trie;
import com.heima.search.model.TrieNode;
import com.heima.search.service.ApAssociateWordsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author feng js
 */
@Service
public class ApAssociateWordsServiceImpl extends ServiceImpl<ApAssociateWordsMapper,ApAssociateWords> implements ApAssociateWordsService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public ResponseResult search(UserSearchDto dto) {

        String associateWordsStr = redisTemplate.opsForValue().get("Associate_words");
        List<ApAssociateWords> apAssociateWords = null;
        if (StringUtils.isNotBlank(associateWordsStr)) {
            apAssociateWords = JSON.parseArray(associateWordsStr, ApAssociateWords.class);
        } else {
             apAssociateWords = list();
            redisTemplate.opsForValue().set("Associate_words",JSON.toJSONString(apAssociateWords));
        }
        Trie trie = new Trie();
        for (ApAssociateWords apAssociateWord : apAssociateWords) {
            trie.insert(apAssociateWord.getAssociateWords());
        }
        List<Map> resultList = new ArrayList<>();
        List<String> list = trie.startWith(dto.getSearchWords());
        for (String s : list) {
            Map<String, String> map = new HashMap<>();
            map.put("associateWords",s);
            resultList.add(map);
        }

        return ResponseResult.okResult(resultList);
    }
}
